package com.clickpaas.workinghours.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.clickpaas.workinghours.config.AutoLoadConfig;
import com.clickpaas.workinghours.entity.UserEntity;
import com.clickpaas.workinghours.service.UserService;
import com.clickpaas.workinghours.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    /**
     * 查询用户登陆信息
     *
     * @return
     */
    @Override
    public UserEntity getUserInfo(String token) {
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> entity = new HttpEntity<String>("parameters", getHeader(token));
        ResponseEntity<Object> result = restTemplate.exchange(AutoLoadConfig.URL, HttpMethod.GET, entity, Object.class);
        if (result.getStatusCode() == HttpStatus.OK) {
            Object body = result.getBody();
            if (null != body){
                JSONObject jsBody = JsonUtil.objToJson(body);
                if (null != jsBody.get("data")){
                    Object data = jsBody.get("data");
                    JSONObject jsData = JsonUtil.objToJson(data);
                    if (StringUtils.isNotBlank(jsData.getString("userInfoRDTO"))){
                        String userInfoRDTO = jsData.getString("userInfoRDTO");
                        return JSONObject.parseObject(userInfoRDTO, UserEntity.class);
                    }
                }
            }
        }
        return null;
    }

    /**
     * 请求头
     * @param token
     * @return
     */
    private HttpHeaders getHeader(String token){
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        headers.set("Cookie", "tokenId=" + token);
        return headers;
    }
}
